﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace SillyCube
{
    public class TouchPanel : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerMoveHandler
    {
        private bool pressed = false;
        private Vector3 pointerPosition;
        
        public void OnPointerDown(PointerEventData eventData)
        {
            var mainCam = Camera.main;

            if (mainCam is null)
                return;
            
            var worldPoint2D = (Vector2) mainCam.ScreenToWorldPoint(eventData.position);
            
            pressed = true;
            GameManager.Instance.OnTouchStateChanged(worldPoint2D, true);
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            var mainCam = Camera.main;

            if (mainCam is null)
                return;
            
            var worldPoint2D = (Vector2) mainCam.ScreenToWorldPoint(eventData.position);
            
            pressed = false;
            GameManager.Instance.OnTouchStateChanged(worldPoint2D, false);
        }

        private void Update()
        {
            if (pressed)
            {
                var touchScrPos = pointerPosition;
                
                var mainCam = Camera.main;
                if (mainCam is not null)
                {
                    var worldPoint3D = mainCam.ScreenToWorldPoint(touchScrPos);
                    
                    GameManager.Instance.OnDrag(new Vector2(worldPoint3D.x, worldPoint3D.y));
                }
            }
        }

        public void OnPointerMove(PointerEventData eventData)
        {
            pointerPosition = eventData.position;
        }
    }
}